Completed
Push — main ( dafebc...2a7c24 )
by Alejandro
17s queued 10s
created

boundToMercureHub.tsx ➔ boundToMercureHub   A

Complexity

Conditions 4

Size

Total Lines 28
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.2596

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 28
ccs 8
cts 14
cp 0.5714
rs 9.232
c 0
b 0
f 0
cc 4
crap 5.2596
1
import { FC, useEffect } from 'react';
2
import { pipe } from 'ramda';
3
import { CreateVisit } from '../../visits/types';
4
import { MercureInfo } from '../reducers/mercureInfo';
5
import { bindToMercureTopic } from './index';
6
7
export interface MercureBoundProps {
8
  createNewVisits: (createdVisits: CreateVisit[]) => void;
9
  loadMercureInfo: Function;
10
  mercureInfo: MercureInfo;
11
}
12
13
export function boundToMercureHub<T = {}>(
14
  WrappedComponent: FC<MercureBoundProps & T>,
15
  getTopicForProps: (props: T) => string,
16
) {
17 8
  const pendingUpdates = new Set<CreateVisit>();
18
19 8
  return (props: MercureBoundProps & T) => {
20 13
    const { createNewVisits, loadMercureInfo, mercureInfo } = props;
21 13
    const { interval } = mercureInfo;
22
23 13
    useEffect(() => {
24 2
      const onMessage = (visit: CreateVisit) => interval ? pendingUpdates.add(visit) : createNewVisits([ visit ]);
25
      const closeEventSource = bindToMercureTopic(mercureInfo, getTopicForProps(props), onMessage, loadMercureInfo);
26
27 2
      if (!interval) {
28
        return closeEventSource;
29
      }
30
31
      const timer = setInterval(() => {
32
        createNewVisits([ ...pendingUpdates ]);
33
        pendingUpdates.clear();
34
      }, interval * 1000 * 60);
35
36
      return pipe(() => clearInterval(timer), () => closeEventSource?.());
37
    }, [ mercureInfo ]);
38
39 13
    return <WrappedComponent {...props} />;
40
  };
41
}
42